package com.wyix;

import com.wyix.aop.CglibProxyInterceptor;
import com.wyix.aop.JdkProxyHandler;
import com.wyix.service.MemberService;
import com.wyix.service.impl.MemberServiceImpl;
import com.wyix.service.impl.VipService;
import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

/**
 * @author wangdx
 * @since 2025/8/6
 */
public class App {
    public static void main(String[] args) {
        // ========== JDK动态代理测试 ==========
        MemberService realMemberService = new MemberServiceImpl();
        JdkProxyHandler jdkHandler = new JdkProxyHandler(realMemberService, "user123");
        MemberService jdkProxy = (MemberService) Proxy.newProxyInstance(
                realMemberService.getClass().getClassLoader(),
                realMemberService.getClass().getInterfaces(),
                jdkHandler
        );

        // 测试正常调用（登录用户自己操作）
        System.out.println("===== JDK代理-正常调用 ====");
        String addResult = jdkProxy.addPoints("user123", 50);  // 登录用户=操作用户
        System.out.println("最终结果：" + addResult);

        // 测试越权调用（登录用户为他人操作）
        System.out.println("\n===== JDK代理-越权调用 ====");
        addResult = jdkProxy.addPoints("user456", 30);  // 登录用户≠操作用户
        System.out.println("最终结果：" + addResult);

        // ========== CGLIB动态代理测试 ==========
        VipService realVipService = new VipService();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(VipService.class);  // 设置父类（被代理类）
        enhancer.setCallback(new CglibProxyInterceptor(realVipService));
        VipService cglibProxy = (VipService) enhancer.create();

        // 测试正常调用（合法VIP等级）
        System.out.println("\n===== CGLIB代理-正常调用 ====");
        String upgradeResult = cglibProxy.upgradeVip("user123", 3);
        System.out.println("最终结果：" + upgradeResult);

        // 测试异常调用（非法VIP等级）
        System.out.println("\n===== CGLIB代理-异常调用 ====");
        upgradeResult = cglibProxy.upgradeVip("user123", 6);
        System.out.println("最终结果：" + upgradeResult);
    }
}
